package com.itheima02.dao;

import com.itheima02.domain.Student;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;


import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class StudentMapper implements StudentInterface {
    @Override
    public List findAll() throws IOException {
        InputStream is = Resources.getResourceAsStream("MybatisConfig.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        List<Student> stu = sqlSession.selectList("student.selectAll");
        return stu;
    }

    @Override
    public void insert(Student stu) throws IOException {
        InputStream is = Resources.getResourceAsStream("MybatisConfig.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        int insert = sqlSession.insert("student.insert",stu);
        System.out.println(insert);
        is.close();
        sqlSession.close();
    }

    @Override
    public void delete(String id) throws IOException {
InputStream is=Resources.getResourceAsStream("MybatisConfig.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        int i = sqlSession.delete("student.delete", id);
        System.out.println(i);
        is.close();
        sqlSession.close();

    }

    @Override
    public void update(Student stu) throws IOException {
        InputStream is=Resources.getResourceAsStream("MybatisConfig.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        int update = sqlSession.update("student.update",stu);
        System.out.println(update);
        is.close();
        sqlSession.close();

    }

    @Override
    public Student findById(String id) throws IOException {
        InputStream is = Resources.getResourceAsStream("MybatisConfig.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        Student stu = sqlSession.selectOne("student.selectOne", id);
        return stu;
    }
}
